package com.starpl.mobile.android.monthunsae.november.handler;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;

import com.starpl.mobile.android.monthunsae.november.R;
import com.starpl.mobile.android.monthunsae.november.activity.CommunityActivity;
import com.starpl.mobile.android.monthunsae.november.activity.HomeActivity;
import com.starpl.mobile.android.monthunsae.november.activity.WriteActivity;
import com.starpl.mobile.android.monthunsae.november.domain.Keyword;
import com.starpl.mobile.android.monthunsae.november.domain.UserInfo;
import com.starpl.mobile.android.platform.command.StarplCommand;
import com.starpl.mobile.android.platform.common.ActivityUtil;
import com.starpl.mobile.android.platform.common.base.BaseApplication;
import com.starpl.mobile.android.platform.common.network.HttpHandler;
import com.starpl.mobile.android.platform.component.BaseListHandler;

public class KeywordListHandler extends BaseListHandler implements OnClickListener
{
	private ArrayList<Keyword> mList;
	
	@SuppressWarnings("unchecked")
	public KeywordListHandler(Activity activity)
	{
		super(activity);
		this.mList = (ArrayList<Keyword>) BaseApplication.getGlobalPersistent("keywordList");
	}

	@Override
	public ArrayList<?> getArrayList()
	{
		return mList;
	}

	@Override
	public View getRowView(int position, View convertView)
	{
		Keyword keyword = mList.get(position);
		
		if(convertView == null)
		{
			convertView = inflate(R.layout.add_community_row);
		}
		
		if(keyword != null)
		{
			TextView tvKeywordName = (TextView)convertView.findViewById(R.id.add_community_row_tv_keywordName);
			ImageButton ibPreview = (ImageButton)convertView.findViewById(R.id.add_community_row_ib_preview);
			ImageButton ibAdd = (ImageButton)convertView.findViewById(R.id.add_community_row_ib_add);
			ImageButton ibDel = (ImageButton)convertView.findViewById(R.id.add_community_row_ib_del);
			
			tvKeywordName.setText(keyword.getKeywordName());
			
			if(keyword.isUseFlag())
			{
				ibAdd.setVisibility(ImageButton.INVISIBLE);
				ibDel.setVisibility(ImageButton.VISIBLE);
			}
			else
			{
				ibAdd.setVisibility(ImageButton.VISIBLE);
				ibDel.setVisibility(ImageButton.INVISIBLE);
			}
			
			ibPreview.setTag(position);
			ibAdd.setTag(position);
			ibDel.setTag(position);
			
			ibPreview.setOnClickListener(this);
			ibAdd.setOnClickListener(this);
			ibDel.setOnClickListener(this);
		}

		return convertView;
	}

	@Override
	public void onRowClick(View v)
	{

	}

	@Override
	public void onRowClear()
	{
		mList.clear();
	}

	@Override
	public void loadContent()
	{
//		notifyDataSetChanged();
	}

	@Override
	public void onInit()
	{
		setAdapter();
		loadContent();
	}

	/**
	 * 커뮤니티를 추가한다.
	 * 
	 * @param keyword 키워드 객체
	 * @param position 키워드 객체가 있는 키워드 리스트의 포지션
	 */
	private void addCommunity(final Keyword keyword, final int position)
	{
		UserInfo userInfo = (UserInfo)BaseApplication.getGlobalPersistent("userInfo");
		
		StarplCommand.registerKeyword(new HttpHandler((Activity)mParentActivity, "커뮤니티를 추가중입니다")
		{
			@Override
			public void didSucceed(Object result)
			{
				writePost(keyword.getKeywordIdx(), keyword.getKeywordName());
				keyword.setUseFlag(true);
				mList.set(position, keyword);
				notifyDataSetChanged();
			}
		}, userInfo.getUserId(), keyword.getKeywordIdx());
	}
	
	/**
	 * 커뮤니티를 삭제한다.
	 * 
	 * @param keyword 키워드 객체
	 * @param position 키워드 객체가 있는 키워드 리스트의 포지션
	 */
	private void delCommunity(final Keyword keyword, final int position)
	{
		UserInfo userInfo = (UserInfo)BaseApplication.getGlobalPersistent("userInfo");
		
		StarplCommand.deleteKeyword(new HttpHandler((Activity)mParentActivity, "커뮤니티를 추가중입니다")
		{
			@Override
			public void didSucceed(Object result)
			{
				keyword.setUseFlag(false);
				mList.set(position, keyword);
				notifyDataSetChanged();
			}
		}, userInfo.getUserId(), keyword.getKeywordIdx());
	}
	
	/**
	 * 글 작성 다이얼로그를 생성한다
	 * 
	 * @param keywordIdx
	 * @param keywordName
	 */
	private void writePost(final int keywordIdx, final String keywordName)
	{
		DialogInterface.OnClickListener writeListener = new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				Bundle extras = new Bundle();
				extras.putInt("keywordIdx", keywordIdx);
				extras.putInt("subKeywordIdx", keywordIdx);
				extras.putString("title", "글쓰기");
				extras.putString("middleTitle", "글쓰기");
				extras.putString("middleContent", keywordName);
				extras.putInt("type", WriteActivity.TYPE_POST);
				
				ActivityUtil activityUtil = new ActivityUtil(mParentActivity);
				activityUtil.setTargetActivity(CommunityActivity.class);
				activityUtil.setBundle(extras);
				activityUtil.setRemoveToActivity(HomeActivity.class);
				activityUtil.show();
				
				Intent intent = new Intent(mParentActivity, WriteActivity.class);
				intent.putExtras(extras);
				mParentActivity.startActivity(intent);
			}
		};

		DialogInterface.OnClickListener cancelListener = new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		};

		String text = "홈 화면에 " + "'" + keywordName +"' <br>" + " 커뮤니티가 추가되었습니다." +
				"<br>커뮤니티에 대한 글을<br> " + "남겨보시겠습니까?"; 
		
		new AlertDialog.Builder(mParentActivity)
			.setTitle(BaseApplication.getConfigPersistent("appsName"))
			.setMessage(Html.fromHtml(text))
			.setPositiveButton("글작성", writeListener)
			.setNegativeButton("취소", cancelListener)
			.show();
	}
	
	private void deleteKeyword(final Keyword keyword, final int position)
	{
		DialogInterface.OnClickListener deleteListener = new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				delCommunity(keyword, position);
			}
		};

		DialogInterface.OnClickListener cancelListener = new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		};

		String text = "홈 화면에서 " + "'" + keyword.getKeywordName() +"' <br>" + " 커뮤니티를 삭제합니다." +
				"<br>정말 삭제하시겠습니까?"; 
		
		new AlertDialog.Builder(mParentActivity)
			.setTitle(BaseApplication.getConfigPersistent("appsName"))
			.setMessage(Html.fromHtml(text))
			.setPositiveButton("삭제", deleteListener)
			.setNegativeButton("취소", cancelListener)
			.show();
	}

	@Override
	public void onClick(View v)
	{
		final int position = (Integer)v.getTag();
		
		final Keyword keyword = mList.get(position);
		final int keywordIdx = keyword.getKeywordIdx();
		
		switch(v.getId())
		{
		
		// 미리보기 클릭
		case R.id.add_community_row_ib_preview:
			Bundle extras = new Bundle();
			extras.putInt("keywordIdx", keywordIdx);

			new ActivityUtil(mParentActivity)
				.setTargetActivity(CommunityActivity.class)
				.setBundle(extras)
				.show();

			return;
		
		// 커뮤니티 추가버튼 클릭
		case R.id.add_community_row_ib_add:
			addCommunity(keyword, position);
			return;
			
		// 커뮤니티 삭제버튼 클릭
		case R.id.add_community_row_ib_del:
			deleteKeyword(keyword, position);
			return;
		}
	}

}
